#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from command.handler import dict_handler
from utility import tools
import logging

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)

class CallBackListAPI(Resource):
    """
    召回记录详情list
    :request: get
    :param archivesId: 档案ID
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        try:
            #  参数校验
            params = request.values
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            #  根据任务类型回显随访记录
            odoo = OdooManager().get_instance()
            #  构造查询条件
            query_ = [
                    ('archives_id', '=', int(params.get('archivesId'))),
                    ('follow_data_type', '=', '2')
                ]   
            fields_ = [
                    'start_time','follow_yz','call_back_doctor','follow_type',
                    'call_back_remark','call_res_remark','call_res'
                ]
            inspection_follow_recall = odoo.env['inspection.follow.recall'].search_read(query_,fields_,order = 'start_time')
            data_ = {'dataList': []}
            if inspection_follow_recall:
                for record_ in inspection_follow_recall:
                    data_list = {
                        'zhsj': record_['start_time'],
                        'yz': record_['follow_yz'],
                        'zhcs': '第{}次'.format(tools.num_to_char(inspection_follow_recall.index(record_)+1)),
                        'zhysName': record_['call_back_doctor'][1] if record_['call_back_doctor'] else '',
                        'zhfs': record_['follow_type'],
                        'yy': record_['call_res_remark'],
                        'callRes': record_['call_res'],
                        'yyfgx': dict_handler.get_dict_value(record_['call_back_remark'],'ck_call_back_relation')
                    }
                    data_['dataList'].append(data_list)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class GetCardListAPI(Resource):
    """
    取单记录详情list
    :request: get
    :param archivesId: 档案ID
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        try:
            #  参数校验
            params = request.values
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            #  根据任务类型回显随访记录
            odoo = OdooManager().get_instance()
            #  构造查询条件
            query_ = [('archives_id', '=', int(params.get('archivesId')))]   
            fields_ = [
                    'qdsj','zxys_id','qdzxm','qdryyygx'
                ]
            birth_before_record = odoo.env['birth.before.record'].search_read(query_,fields_,order = 'qdsj')
            data_ = {'dataList': []}
            if birth_before_record:
                for record_ in birth_before_record:
                    data_list = {
                        'qdsj': record_['qdsj'],
                        'zxysName': record_['zxys_id'][1] if record_['zxys_id'] else '',
                        'qdzxm': record_['qdzxm'],
                        'yyfgx': record_['qdryyygx']
                    }
                    data_['dataList'].append(data_list)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class Week28ListAPI(Resource):
    """
    孕28周回访记录详情list
    :request: get
    :param archivesId: 档案ID
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        try:
            #  参数校验
            params = request.values
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            #  根据任务类型回显随访记录
            odoo = OdooManager().get_instance()
            #  构造查询条件
            query_ = [
                    ('archives_id', '=', int(params.get('archivesId'))),
                    ('follow_data_type', '=', '3')
                ]    
            fields_ = [
                    'start_time','check_hospital','check_type','check_res',
                    'follow_yz','call_back_remark','jyb_check'
                ]
            inspection_follow_recall = odoo.env['inspection.follow.recall'].search_read(query_,fields_,order = 'start_time')
            data_ = {'dataList': []}
            tmp_map = {'0': '本人' , '1': '老公','2': '其他'}
            if inspection_follow_recall:
                for record_ in inspection_follow_recall:
                    data_list = {
                        'y28zsj': record_['follow_yz'],
                        'hfrq': record_['start_time'],
                        'jcysName': record_['check_hospital'],
                        'jcfs': dict_handler.get_dict_value(record_['check_type'],'ck_check_type'),
                        'jcjg': record_['check_res'],
                        'sfjjjybjc': record_['jyb_check'],
                        'yyfgx': dict_handler.get_dict_value(record_['call_back_remark'],'ck_call_back_relation')
                    }
                    data_['dataList'].append(data_list)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class RcResultListAPI(Resource):
    """
    妊娠结局回访记录详情list
    :request: get
    :param archivesId: 档案ID
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        try:
            #  参数校验
            params = request.values
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            #  根据任务类型回显随访记录
            odoo = OdooManager().get_instance()
            #  构造查询条件
            query_ = [
                    ('archives_id', '=', int(params.get('archivesId'))),
                    ('follow_data_type', '=', '4')
                ]    
            fields_ = [
                    'start_time','follow_type','state','user_id',
                    'fm_hospital','fm_type','rc_ju','rc_ju_remark'
                ]
            inspection_follow_recall = odoo.env['inspection.follow.recall'].search_read(query_,fields_,order = 'start_time')
            data_ = {'dataList': []}
            if inspection_follow_recall:
                for record_ in inspection_follow_recall:
                    data_list = {
                        'sfsj': record_['start_time'],
                        'sffs': dict_handler.get_dict_value(record_['follow_type'],'ck_follow_type'),
                        'sfjg': dict_handler.get_dict_value(record_['state'],'ck_follow_status'),
                        'zxysName': record_['user_id'][1] if record_['user_id'] else '',
                        'sbyy': '',
                        'fmyy': record_['fm_hospital'],
                        'fmfs': record_['fm_type'],
                        'rsjj': record_['rc_ju'],
                        'ycwt': record_['rc_ju_remark']
                    }
                    data_['dataList'].append(data_list)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class CqscHighRiskProStaGetAPI(Resource):
    """
    产前筛查高危风险专案 上部统计数据
    :request: get
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):

        try:
            #  个案总数
            params = request.values
            odoo = OdooManager().get_instance()
            #  已结案个案总数
            high_risk_today_ct = odoo.env['res_archives'].search_count([
                   ('max_gwys', '>', 0), ('max_gwys', '<', 5),
                   ('status', '=', '0'),('jd_date', '>=', datetime.strftime(datetime.today(), "%Y-%m-%d"))
                ])
            #  管理中个案
            gwzazs_ct = odoo.env['res_archives'].search_count([
                   ('max_gwys', '>', 0), ('max_gwys', '<', 5)
                ])  
            #  本院建档个案    
            jrjagws_  = odoo.env['res_archives'].search_count([
                   ('max_gwys', '>', 0), ('max_gwys', '<', 5),
                   ('status', '=', '1'),('jd_date', '>=', datetime.strftime(datetime.today(), "%Y-%m-%d"))
                ])  
            #  外院建档个案         
            orange_ct = odoo.env['res_archives'].search_count([
                   ('max_gwys', '=', 2)
                ])    
            data_ = {
                'gazs': high_risk_today_ct,
                'yjazs': gwzazs_ct,
                'glzga': jrjagws_,
                'byjdga': orange_ct,
                'yyjdga': red_ct,
            }         
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class OrderRecordAddAPI(Resource):
    """
    新增取单
    :request: post
    :param archivesId: 档案ID
    :param qdryyygx: 取单人与孕妇关系
    :param qdryyygxQt: 取单人与孕妇关系其他
    :param qdrName: 取单人姓名
    :param zxyyCode: 咨询医生code
    :param qzbUrl: 签字表URL
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            # 参数校验
            req_params = ['archivesId','qdryyygx','qdryyygxQt','qdrName','zxyyCode','qzbUrl']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            # 检验是否创建过取单数据 archives_id唯一   
            #query_ = [('archives_id', '=', int(params.get('archivesId')))]
            #birth_before_record = odoo.env['birth.before.record'].search(query_)
            #if  birth_before_record:
            #    return jsonify({'code': 40006, 'msg': error_code[40006]})    
            # 新增模板管理
            data_ = {
                'archives_id': params.get('archivesId'),
                'qdryyygx': params.get('qdryyygx'),
                'qdryyygx_qt': params.get('qdryyygxQt'),
                'qdzxm': params.get('qdrName'),
                'zxys_id': params.get('zxyyCode'),
                'qzb_url': params.get('qzbUrl')
            }
            data_ = odoo.env['birth.before.record'].create(data_)
            create_event = event_type.OperationLogEvent('新增取单', 'id:{}'.format(data_))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {'id': data_}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class OrderRecordQueryAPI(Resource):
    """
    回显取单详情
    :request: get
    :param archivesId: 档案ID
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def get(self):
        try:
            #  参数校验
            params = request.values
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            #  根据任务类型回显随访记录
            odoo = OdooManager().get_instance()
            #  构造查询条件
            query_ = [
                    ('archives_id', '=', int(params.get('archivesId')))
                ]   
            fields_ = [
                    'qdryyygx','qdryyygx_qt','qdzxm','zxys_id',
                    'qzb_url'
                ]
            birth_before_record = odoo.env['birth.before.record'].search_read(query_,fields_)
            data_ = {}
            if birth_before_record:
                record_=birth_before_record[0]
                data_ = {
                    'qdryyygx': record_['qdryyygx'],
                    'qdryyygxQt': record_['qdryyygx_qt'],
                    'qdrName': record_['qdzxm'],
                    'zxyyCode': record_['zxys_id'],
                    'qzbUrl': record_['qzb_url']
                }
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})
